package com.jwgf.common;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.jwgf.mqtt.MqttClientManager;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class CrashHandler implements UncaughtExceptionHandler {
    public static final String TAG = "CrashHandler";
    private static CrashHandler instance = new CrashHandler();
    private Context ctx;
    private UncaughtExceptionHandler defaultHandler;
    private Map<String, String> infos = new HashMap<String, String>();

    private CrashHandler() {
    }

    public static CrashHandler getInstance() {
        return instance;
    }

    public void init(Context ctx) {
        this.ctx = ctx;
        defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        } else {
            new Thread() {
                @Override
                public void run() {
                    Looper.prepare();
                    Toast.makeText(ctx, "很抱歉,程序出现异常,即将退出.", Toast.LENGTH_LONG)
                            .show();
                    Looper.loop();
                }
            }.start();
            collectDeviceInfo(ctx);
            saveCrashInfo2File(ex);
            return true;
        }
    }

    public void collectDeviceInfo(Context ctx) {
        try {
            PackageManager pm = ctx.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(),
                    PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                String versionName = pi.versionName == null ? "null"
                        : pi.versionName;
                String versionCode = pi.versionCode + "";
                infos.put("versionName", versionName);
                infos.put("versionCode", versionCode);
            }
        } catch (NameNotFoundException e) {
            Log.e(TAG, "an error occured when collect package info", e);
        }
        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                infos.put(field.getName(), field.get(null).toString());
                Log.d(TAG, field.getName() + " : " + field.get(null));
            } catch (Exception e) {
                Log.e(TAG, "an error occured when collect crash info", e);
            }
        }
    }

    private void saveCrashInfo2File(Throwable ex) {
        Log.i("crash", ex.toString());
        StringBuffer sb = new StringBuffer();
        sb.append(AppContext.version).append("\n");
        for (Map.Entry<String, String> entry : infos.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            sb.append(key + "=" + value + "\n");
        }

        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace();
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String result = writer.toString();
        sb.append(result);
        try {
//			Calendar calendar = Calendar.getInstance();
//			String created = calendar.get(Calendar.YEAR) + "-"
//					+ (calendar.get(Calendar.MONTH) + 1) + "-"
//					+ calendar.get(Calendar.DAY_OF_MONTH) + "-"
//					+ calendar.get(Calendar.HOUR_OF_DAY) + "-"
//					+ calendar.get(Calendar.MINUTE) + "-"
//					+ calendar.get(Calendar.SECOND);
//
//			File dir = ctx.getFilesDir();
//			String fileName = "crash-" + created + ".log";
//
//			File file = new File(dir, fileName);
//			FileOutputStream fos = new FileOutputStream(file);
//			fos.write(sb.toString().getBytes());
//			fos.flush();
//			fos.close();
            Intent intent = new Intent("com.jwgf.CRASH");
            intent.putExtra("package", ctx.getPackageName());
            intent.putExtra("log", sb.toString());
            ctx.sendBroadcast(intent);

            JSONObject crash = new JSONObject();
            crash.put("ip", IPConfig.getIp());
            crash.put("MAC", IPConfig.getWifiMAC());
            crash.put("id", IPConfig.getMachineID());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年mm月dd日HH:mm:ss", Locale.US);
            crash.put("机台时间", sdf.format(new Date()));
            crash.put("内容", sb.toString());
            MqttClientManager.getInstance().publishMessage("luotongcrash", crash.toString(), 0);
        } catch (Exception e) {
            Log.e(TAG, "an error occured while writing file...", e);
        }
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (!handleException(ex) && defaultHandler != null) {
            defaultHandler.uncaughtException(thread, ex);
        } else {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {

            }
            android.os.Process.killProcess(android.os.Process.myPid());
            // System.exit(1);
        }
    }

}
